package com.itheima.sh.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 全局过滤器，实现登录功能
 * @Version: V1.0
 */
//@Component
//@Order(0)  // 越小越优先越执行 1 6 9 10 14
public class LoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 得到 request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2 获取请求参数 token
        String token = request.getQueryParams().getFirst("token");

        //2.1 请求参数没有token 直接拦截
        if (StringUtils.isBlank(token)) {
            // 设置状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);  // 401
            // 响应给前端
           return response.setComplete();
        }

        //2.2 有token  判断token是否是admin
        // 不是admin 拦截
        if (!"admin".equals(token)) {
            // 设置状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);  // 401
            // 响应给前端
            return response.setComplete();
        }

        // 是admin 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
